import 'package:efood_multivendor/controller/campaign_controller.dart';
import 'package:efood_multivendor/controller/splash_controller.dart';
import 'package:efood_multivendor/controller/theme_controller.dart';
import 'package:efood_multivendor/helper/date_converter.dart';
import 'package:efood_multivendor/helper/price_converter.dart';
import 'package:efood_multivendor/helper/size_config.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/base/custom_image.dart';
import 'package:efood_multivendor/view/base/discount_tag.dart';
import 'package:efood_multivendor/view/base/not_available_widget.dart';
import 'package:efood_multivendor/view/base/product_bottom_sheet.dart';
import 'package:efood_multivendor/view/base/rating_bar.dart';
import 'package:efood_multivendor/view/base/title_widget.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shimmer_animation/shimmer_animation.dart';

import '../../../base/custom_button.dart';

class ItemCampaignView extends StatelessWidget {
  final CampaignController campaignController;
  ItemCampaignView({required this.campaignController});

  @override
  Widget build(BuildContext context) {
    ScrollController _scrollController = ScrollController();

    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Padding(
                padding: EdgeInsets.fromLTRB(10, 15, 10, 10),
                child: TitleWidget(
                  title: 'special_offers'.tr,
                )),
            Get.find<SplashController>()
                        .configModel
                        ?.campaignFilters
                        ?.filters
                        ?.isNotEmpty !=
                    true
                ? SizedBox()
                : Wrap(children: [
                    Padding(
                      padding: const EdgeInsets.only(right: 8.0),
                      child: GestureDetector(
                          onTap: () {
                            Get.bottomSheet(SpecialOffersBottomSheet(),
                                backgroundColor: Colors.white,
                                isDismissible: true);

                            //  Get.to(SpecialOffersBottomSheet());
                            // Get.bottomSheet(
                            // FilterWidget(maxValue: 1000, isRestaurant: true),
                            // isScrollControlled: true,
                            // shape: const RoundedRectangleBorder(
                            //     borderRadius: BorderRadius.vertical(
                            //         top: Radius.circular(25.0))),
                            //   );
                          },
                          child: Container(
                            padding: EdgeInsets.all(3),
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(5),
                                border: Border.all(
                                    color: Theme.of(context)
                                        .colorScheme
                                        .secondary)),
                            child: Center(
                              child: Text(
                                'filter'.tr,
                                style: sfMedium.copyWith(
                                    color:
                                        Theme.of(context).colorScheme.secondary,
                                    fontWeight: FontWeight.bold,
                                    fontSize: Dimensions.fontSizeLarge * 0.87),
                              ),
                            ),
                          )),
                    ),
                  ])
          ],
        ),
        SizedBox(
          height: 150,
          child: campaignController.itemCampaignList.isNotEmpty == true
              ? ListView.builder(
                  controller: _scrollController,
                  physics: BouncingScrollPhysics(),
                  scrollDirection: Axis.horizontal,
                  padding: EdgeInsets.only(left: Dimensions.PADDING_SIZE_SMALL),
                  itemCount: campaignController.itemCampaignList.length,
                  itemBuilder: (context, index) {
                    bool _isAvailable =
                        campaignController.itemCampaignList[index].is_open ??
                            false;

                    return Padding(
                      padding: EdgeInsets.only(
                          right: Dimensions.PADDING_SIZE_SMALL, bottom: 5),
                      child: InkWell(
                        onTap: () async {
                          Get.bottomSheet(
                            ProductBottomSheet(
                                product:
                                    campaignController.itemCampaignList[index],
                                isCampaign: true),
                            backgroundColor: Colors.transparent,
                            isScrollControlled: true,
                          );
                          await FirebaseAnalytics.instance.logEvent(
                              name: 'special_offer_clicked',
                              parameters: {
                                'timestamp':
                                    DateConverter.getCurrentTimeInGmtPlus3()
                                        .toString(),
                                'foodID': campaignController
                                    .itemCampaignList[index].id
                                    .toString(),
                                'restaurantID': campaignController
                                    .itemCampaignList[index].restaurantId
                                    .toString()
                              });
                        },
                        child: Container(
                          height: 150,
                          width: 130,
                          decoration: BoxDecoration(
                            color: Theme.of(context).cardColor,
                            borderRadius:
                                BorderRadius.circular(Dimensions.RADIUS_SMALL),
                            boxShadow: [
                              BoxShadow(
                                color: Colors.grey[
                                    Get.find<ThemeController>().darkTheme
                                        ? 700
                                        : 300]!,
                                blurRadius: 5,
                                spreadRadius: 1,
                              )
                            ],
                          ),
                          child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Stack(children: [
                                  ClipRRect(
                                    borderRadius: BorderRadius.vertical(
                                        top: Radius.circular(
                                            Dimensions.RADIUS_SMALL)),
                                    child: CustomImage(
                                      image:
                                          '${campaignController.itemCampaignList[index].image}',
                                      height: 90,
                                      width: 130,
                                      fit: BoxFit.cover,
                                    ),
                                  ),
                                  DiscountTag(
                                    discount: campaignController
                                                .itemCampaignList[index]
                                                .restaurantDiscount! >
                                            0
                                        ? campaignController
                                            .itemCampaignList[index]
                                            .restaurantDiscount!
                                        : campaignController
                                            .itemCampaignList[index].discount!,
                                    discountType: campaignController
                                                .itemCampaignList[index]
                                                .restaurantDiscount! >
                                            0
                                        ? 'percent'
                                        : campaignController
                                            .itemCampaignList[index]
                                            .discountType!,
                                  ),
                                  _isAvailable
                                      ? SizedBox()
                                      : NotAvailableWidget(),
                                ]),
                                Expanded(
                                  child: Padding(
                                    padding: EdgeInsets.symmetric(
                                        horizontal: Dimensions
                                            .PADDING_SIZE_EXTRA_SMALL),
                                    child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          Text(
                                            campaignController
                                                    .itemCampaignList[index]
                                                    .name ??
                                                '',
                                            style: sfMedium.copyWith(
                                                fontSize:
                                                    Dimensions.fontSizeSmall),
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                          SizedBox(height: 2),
                                          Text(
                                            campaignController
                                                    .itemCampaignList[index]
                                                    .restaurantName ??
                                                '',
                                            style: sfMedium.copyWith(
                                                fontSize: Dimensions
                                                    .fontSizeExtraSmall,
                                                color: Theme.of(context)
                                                    .disabledColor),
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                          SizedBox(height: 2),
                                          Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceAround,
                                            children: [
                                              Text(
                                                PriceConverter.convertPrice(
                                                    campaignController
                                                            .itemCampaignList[
                                                                index]
                                                            .price ??
                                                        0,
                                                    discount: campaignController
                                                        .itemCampaignList[index]
                                                        .discount,
                                                    discountType:
                                                        campaignController
                                                            .itemCampaignList[
                                                                index]
                                                            .discountType,
                                                    asFixed: 1),
                                                style: sfMedium.copyWith(
                                                    fontSize: Dimensions
                                                        .fontSizeSmall),
                                              ),
                                              Flexible(
                                                child: Text(
                                                  '${PriceConverter.convertPrice(campaignController.itemCampaignList[index].price ?? 0)}',
                                                  style: sfMedium.copyWith(
                                                      color: Theme.of(context)
                                                          .disabledColor,
                                                      decoration: TextDecoration
                                                          .lineThrough,
                                                      decorationColor:
                                                          Theme.of(context)
                                                              .disabledColor),
                                                  maxLines: 1,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ]),
                                  ),
                                ),
                              ]),
                        ),
                      ),
                    );
                  },
                )
              : ItemCampaignShimmer(campaignController: campaignController),
        ),
      ],
    );
  }
}

class SpecialOffersBottomSheet extends StatefulWidget {
  @override
  _SpecialOffersScreenState createState() => _SpecialOffersScreenState();
}

class _SpecialOffersScreenState extends State<SpecialOffersBottomSheet> {
  String? selectedFilter = Get.find<SplashController>()
      .configModel
      ?.defaultCampaignFilter
      .toString(); // Default selected filter

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CampaignController>(builder: (campaignController) {
      return Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                InkWell(
                  onTap: () => Navigator.of(context).pop(),
                  child: Padding(
                    padding:
                        EdgeInsets.all(Dimensions.PADDING_SIZE_EXTRA_SMALL),
                    child: Icon(Icons.close,
                        color: Theme.of(context).disabledColor),
                  ),
                ),
                Text(
                  "filter_special_offers".tr,
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                CustomButton(
                  onPressed: () {
                    campaignController.clearFilters();
                    // filterController.clearFilters();
                  },
                  buttonText: 'clear'.tr,
                  transparent: true,
                  width: 26.w,
                ),
              ],
            ),
            Divider(),
            ListView.builder(
              shrinkWrap: true,
              itemCount: Get.find<SplashController>()
                      .configModel
                      ?.campaignFilters
                      ?.filters
                      ?.entries
                      .length ??
                  0,
              itemBuilder: (context, index) {
                final key = Get.find<SplashController>()
                    .configModel!
                    .campaignFilters!
                    .filters!
                    .keys
                    .toList()[index];
                final value = Get.find<SplashController>()
                    .configModel!
                    .campaignFilters!
                    .filters![key];
                return ListTile(
                  title: Text(
                    value ?? '',
                    style: TextStyle(
                        color: campaignController.selectedFilter == key
                            ? Theme.of(context).colorScheme.secondary
                            : Colors.black),
                  ),
                  trailing: campaignController.selectedFilter == key
                      ? Icon(Icons.check,
                          color: Theme.of(context).colorScheme.secondary)
                      : null,
                  onTap: () {
                    campaignController.setSelectedFilter(key);
                  },
                );
              },
            ),
            SizedBox(
              height: 5,
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: CustomButton(
                buttonText: 'apply'.tr,
                radius: 15,
                height: 6.h,
                onPressed: () {
                  Get.back();
                  campaignController.getItemCampaignList(true,
                      filter: campaignController.selectedFilter);
                },
              ),
            ),
            SizedBox(
              height: 15,
            ),
          ],
        ),
      );
    });
  }
}

class ItemCampaignShimmer extends StatelessWidget {
  final CampaignController campaignController;
  ItemCampaignShimmer({required this.campaignController});

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      shrinkWrap: true,
      physics: BouncingScrollPhysics(),
      scrollDirection: Axis.horizontal,
      padding: EdgeInsets.only(left: Dimensions.PADDING_SIZE_SMALL),
      itemCount: 10,
      itemBuilder: (context, index) {
        return Container(
          height: 150,
          width: 130,
          margin:
              EdgeInsets.only(right: Dimensions.PADDING_SIZE_SMALL, bottom: 5),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(Dimensions.RADIUS_SMALL),
              boxShadow: [
                BoxShadow(
                    color: Colors.grey[300]!, blurRadius: 10, spreadRadius: 1)
              ]),
          child: Shimmer(
            duration: Duration(seconds: 2),
            enabled: campaignController.itemCampaignList.isEmpty,
            child:
                Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Container(
                height: 90,
                width: 130,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.vertical(
                        top: Radius.circular(Dimensions.RADIUS_SMALL)),
                    color: Colors.grey[300]),
              ),
              Expanded(
                child: Padding(
                  padding: EdgeInsets.all(Dimensions.PADDING_SIZE_EXTRA_SMALL),
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                            height: 10, width: 100, color: Colors.grey[300]),
                        SizedBox(height: 5),
                        Container(
                            height: 10, width: 130, color: Colors.grey[300]),
                        SizedBox(height: 5),
                        Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Container(
                                  height: 10,
                                  width: 30,
                                  color: Colors.grey[300]),
                              RatingBar(rating: 0.0, size: 12, ratingCount: 0),
                            ]),
                      ]),
                ),
              ),
            ]),
          ),
        );
      },
    );
  }
}
